package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.domain.dto.SubAccountQueryDTO;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.http.KuJiaLeHttpUtil;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IAccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
@Slf4j
public class AccountServiceImpl implements IAccountService {

    private static final String BASE_URL = "https://openapi.kujiale.com";

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public String getToken(String userId, String dest) {
        JSONObject param = new JSONObject();
        param.put("appuid", userId);
        param.put("dest", dest);
        KuJiaLeHttpUtil.ApiResponse<String> post = KuJiaLeHttpUtil.post("https://openapi.kujiale.com/v2/sso/token", param, null, String.class);
        if (post.isSuccess()){
            return post.getData();
        }
        throw new ServiceException("获取失败:"+post.getMessage());
    }

    @Override
    public boolean register(String appUid, String userId, String userName, String email,
                            String avatar, Integer type, String defaultPassword,
                            String departmentNodeId, String kujialeBindReason) {

        SysUser sysUser = sysUserMapper.selectUserById(Long.valueOf(userId));
        if (sysUser == null || "1".equals(sysUser.getStatus()) || "2".equals(sysUser.getDelFlag())) {
            throw new ServiceException("用户不存在或已被禁用");
        }

        if (sysUser.getKujialeId() != null && sysUser.getKujialeStatus() == 1) {
            throw new ServiceException("用户已绑定子账号");
        }

        // 1. 构建请求URL
        String url = BASE_URL + "/v2/register";

        // 2. 准备URL参数（包含appuid，因为注册接口必须传）
        JSONObject urlParams = new JSONObject();
        urlParams.put("appuid", appUid);

        // 3. 构建请求体JSON
        JSONObject requestBody = new JSONObject();
        requestBody.put("name", userName);

        // 可选参数处理
        if (StringUtils.isNotBlank(email)) {
            requestBody.put("email", email);
        }
        if (StringUtils.isNotBlank(avatar)) {
            requestBody.put("avatar", avatar);
        }
        // 设置用户类型，默认0
        requestBody.put("type", type != null ? type : 0);

        if (StringUtils.isNotBlank(defaultPassword)) {
            requestBody.put("defaultPassword", defaultPassword);
        }
        if (StringUtils.isNotBlank(departmentNodeId)) {
            requestBody.put("departmentNodeId", departmentNodeId);
        }

        // 4. 调用现有的POST方法，内部会使用buildUrlWithParams处理鉴权
        KuJiaLeHttpUtil.ApiResponse post = KuJiaLeHttpUtil.post(url, urlParams, requestBody.toJSONString());
        if (post.isSuccess() && "0".equals(post.getCode())) {
            sysUser.setIsBindKujiale(1);
            sysUser.setKujialeId(appUid);
            sysUser.setKujialeStatus(1);
            sysUser.setKujialeBindReason(kujialeBindReason);
            sysUserMapper.updateById(sysUser);
            return true;
        } else {
            log.error("子账号注册失败: {}", post.getMessage());
            throw new ServiceException(post.getMessage());
        }
    }

    /**
     * 账号解绑
     */
    @Override
    public boolean unbind(String userId) {
        SysUser sysUser = sysUserMapper.selectById(Long.valueOf(userId));
        if (sysUser == null) {
            throw new ServiceException("用户不存在");
        }

        if (sysUser.getKujialeId() == null && sysUser.getIsBindKujiale() == 0 && sysUser.getKujialeStatus() == 0 ) {
            throw new ServiceException("用户未绑定该子账号");
        }

        sysUser.setKujialeId(null);
        sysUser.setIsBindKujiale(0);
        sysUser.setKujialeStatus(0);
        sysUserMapper.updateById(sysUser);
        return true;
    }

    /**
     * 账号换绑
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean rebind(String appUid, String userId,String oldUserId, String kujialeBindReason, String kujialeRebindReason) {
        // 1. 验证原用户是否存在且已绑定
        SysUser sysUser = sysUserMapper.selectById(Long.valueOf(userId));

        if (sysUser == null || "1".equals(sysUser.getStatus()) || "2".equals(sysUser.getDelFlag())) {
            throw new ServiceException("用户不存在或已被禁用");
        }

        // 3. 验证新用户是否已绑定其他子账号
        if (StringUtils.isNotBlank(sysUser.getKujialeId()) || sysUser.getKujialeStatus() == 1 || sysUser.getIsBindKujiale() == 1) {
            throw new ServiceException("用户已绑定其他子账号");
        }

        if (StringUtils.isBlank(sysUser.getEmail())) {
            throw new ServiceException("请新绑定用户前往个人中心绑定邮箱后重试");
        }

        SysUser oldUser = sysUserMapper.selectUserById(Long.valueOf(oldUserId));
        oldUser.setKujialeRebindReason(kujialeRebindReason);
        oldUser.setKujialeStatus(0);
        oldUser.setIsBindKujiale(0);
        oldUser.setKujialeId(null);

        // 4. 构建请求URL (使用账号换人接口)
        String changeBindUrl = BASE_URL + "/v2/account/change-bind";
        String editInfoUrl = BASE_URL + "/v2/account/update";

        // 6. 构建请求体 (假设需要设置新邮箱和密码)
        JSONObject changeBindReq = new JSONObject();
        changeBindReq.put("appuid", appUid);
        // 这里可以根据实际情况从新用户信息中获取邮箱
        changeBindReq.put("email", StringUtils.isNotBlank(sysUser.getEmail()) ? sysUser.getEmail() : "");
        // 密码可以使用默认密码或新用户密码
        changeBindReq.put("pwd", "DefaultPassword123"); // 这里使用一个默认密码，实际应用中应更安全地处理

        // 7. 调用POST方法
        KuJiaLeHttpUtil.ApiResponse post = KuJiaLeHttpUtil.post(changeBindUrl, null, changeBindReq.toJSONString());
        if (post.isSuccess() && "0".equals(post.getCode())) {

            // 6. 构建请求体 (假设需要设置新邮箱和密码)
//            JSONObject editInfoReq = new JSONObject();
//            JSONObject account = new JSONObject();
//            account.put("name", sysUser.getUserName());
//            editInfoReq.put("appuid", appUid);
//            editInfoReq.put("account", account);
//            KuJiaLeHttpUtil.post(editInfoUrl, null, editInfoReq.toJSONString());

            // 9. 更新新用户绑定状态
            sysUser.setIsBindKujiale(1);
            sysUser.setKujialeId(appUid);
            sysUser.setKujialeStatus(1);
            sysUser.setKujialeBindReason(kujialeBindReason);
            sysUser.setKujialeRebindReason(kujialeRebindReason);
            sysUserMapper.updateById(sysUser);
            sysUserMapper.updateById(oldUser);

            return true;
        }
        return false;
    }

    /**
     * 查询子账号列表
     */
    @Override
    public Object querySubAccountList(SubAccountQueryDTO queryDTO) {
        // 参数校验
        if (queryDTO == null) {
            queryDTO = new SubAccountQueryDTO();
        }

        // 2. 构建请求URL并校验
        String url = BASE_URL + "/v2/account/search/v2";

        // 3. 构建请求体 (添加必要的参数校验)
        JSONObject requestBody = new JSONObject();
        try {
            requestBody.put("start", queryDTO.getStart() != null ? queryDTO.getStart() : 0);  // 分页起始点
            requestBody.put("num", Math.min(queryDTO.getNum() != null ? queryDTO.getNum() : 50, 500));  // 确保不超过最大限制
            requestBody.put("nodeFilterType", 0);  // 0：当前节点及子节点
            requestBody.put("nodeId", "3FO4K65MOW41");  // 考虑是否需要参数化此值
        } catch (Exception e) {
            throw new ServiceException("构建请求参数失败: " + e.getMessage());
        }

        // 4. 调用POST方法并处理可能的异常
        KuJiaLeHttpUtil.ApiResponse post;
        try {
            post = KuJiaLeHttpUtil.post(url, null, requestBody.toJSONString());
        } catch (Exception e) {
            throw new ServiceException("调用接口时发生异常: " + e.getMessage());
        }

        // 6. 处理接口响应
        if (!post.isSuccess()) {
            throw new ServiceException(String.format("查询子账号列表失败: 状态码=%s, 消息=%s",
                    post.getCode(), post.getMessage()));
        }

        // 7. 处理返回数据
        Object rawData = post.getData();
        if (rawData == null) {
            throw new ServiceException("接口返回数据为空");
        }

        try {
            // 安全转换为JSONObject
            JSONObject data = JSONObject.from(rawData);

            // 检查result数组是否存在
            if (!data.containsKey("result")) {
                return null;
            }

            JSONArray result = data.getJSONArray("result");
            if (result == null) {
                return null;
            }

            // 过滤后的结果列表
            JSONArray filteredResult = new JSONArray();

            // 遍历处理每个用户
            for (Object o : result) {
                if (!(o instanceof JSONObject)) {
                    continue; // 跳过非JSONObject类型的元素
                }

                JSONObject user = (JSONObject) o;
                JSONObject account = user.getJSONObject("account"); // 使用opt避免空指针
                if (account == null) {
                    continue; // 没有account信息则跳过
                }

                String appUid = account.getString("appUid");
                if (appUid == null || appUid.trim().isEmpty()) {
                    continue; // appUid为空则跳过
                }

                // 应用子账号状态过滤条件（基于子API返回的status字段）
                boolean shouldInclude = true;
                
                // 子账号状态过滤（子账号状态：0-正常 1-删除 2-禁用 3-邀请中）
                if (queryDTO.getSubAccountStatus() != null) {
                    Integer accountStatus = account.getInteger("status");
                    if (accountStatus == null || !accountStatus.equals(queryDTO.getSubAccountStatus())) {
                        shouldInclude = false;
                    }
                }
                
                // 子账号名称过滤（子账号名称）
                if (shouldInclude && StringUtils.isNotBlank(queryDTO.getSubAccountName())) {
                    String accountName = account.getString("name");
                    if (accountName == null || !accountName.contains(queryDTO.getSubAccountName())) {
                        shouldInclude = false;
                    }
                }

                // 查询本地用户（用于绑定状态、设计师名称、设计师手机号过滤）
                List<SysUser> sysUserList;
                if (shouldInclude && (queryDTO.getIsBindSubAccount() != null ||
                    StringUtils.isNotBlank(queryDTO.getDesignerName()) || 
                    StringUtils.isNotBlank(queryDTO.getDesignerPhone()))) {
                    try {
                        LambdaQueryWrapper<SysUser> sysUserWrapper = Wrappers.lambdaQuery();
                        sysUserWrapper.eq(SysUser::getKujialeId, appUid);
                        
                        // 根据查询条件构建本地用户查询条件
                        if (queryDTO.getIsBindSubAccount() != null) {
                            sysUserWrapper.eq(SysUser::getIsBindKujiale, queryDTO.getIsBindSubAccount());
                        }
                        if (StringUtils.isNotBlank(queryDTO.getDesignerName())) {
                            sysUserWrapper.like(SysUser::getNickName, queryDTO.getDesignerName());
                        }
                        if (StringUtils.isNotBlank(queryDTO.getDesignerPhone())) {
                            sysUserWrapper.like(SysUser::getPhonenumber, queryDTO.getDesignerPhone());
                        }
                        
                        sysUserList = sysUserMapper.selectList(sysUserWrapper);
                    } catch (Exception e) {
                        // 记录日志但不中断整个流程
                        log.error("查询本地用户失败，appUid: {}", appUid, e);
                        sysUserList = Collections.emptyList();
                    }
                } else {
                    // 如果没有本地用户相关的过滤条件，查询所有绑定的用户
                    try {
                        LambdaQueryWrapper<SysUser> sysUserWrapper = Wrappers.lambdaQuery();
                        sysUserWrapper.eq(SysUser::getKujialeId, appUid);
                        sysUserList = sysUserMapper.selectList(sysUserWrapper);
                    } catch (Exception e) {
                        log.error("查询本地用户失败，appUid: {}", appUid, e);
                        sysUserList = Collections.emptyList();
                    }
                }
                
                user.put("localUser", sysUserList != null ? sysUserList : Collections.emptyList());

                // 最终过滤逻辑：如果设置了本地用户相关过滤条件，必须有匹配的本地用户
                if (shouldInclude) {
                    boolean hasLocalUserFilter = queryDTO.getIsBindSubAccount() != null ||
                        StringUtils.isNotBlank(queryDTO.getDesignerName()) || 
                        StringUtils.isNotBlank(queryDTO.getDesignerPhone());
                    
                    if (!hasLocalUserFilter || !Objects.requireNonNull(sysUserList).isEmpty()) {
                        filteredResult.add(user);
                    }
                }
            }

            // 更新返回数据中的result数组
            data.put("result", filteredResult);
            data.put("count", filteredResult.size());
            return data;
        } catch (JSONException e) {
            throw new ServiceException("解析接口返回数据失败: " + e.getMessage());
        } catch (Exception e) {
            throw new ServiceException("处理子账号列表时发生异常: " + e.getMessage());
        }
    }

    /**
     * 获取账号上限和数量信息
     */
    @Override
    public Object getAccountLimitInfo(String appUid) {
        // 1. 构建请求URL
        String url = BASE_URL + "/v2/account/limit-info";

        // 3. 调用GET方法
        KuJiaLeHttpUtil.ApiResponse response = KuJiaLeHttpUtil.get(url);
        if (response.isSuccess()) {
            return response.getData();  // 假设ApiResponse有获取数据的方法
        }
        throw new ServiceException("获取账号上限和数量信息失败: " + response.getMessage());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean disableKujialeAccount(String appUid) {
        log.info("开始禁用子账号，appUid: {}", appUid);
        
        // 1. 验证参数
        if (StringUtils.isBlank(appUid)) {
            throw new ServiceException("子账号ID不能为空");
        }
        
        // 3. 查找本地用户
        LambdaQueryWrapper<SysUser> userWrapper = Wrappers.lambdaQuery();
        userWrapper.eq(SysUser::getKujialeId, appUid)
                .eq(SysUser::getKujialeStatus, 1)
                .eq(SysUser::getIsBindKujiale, 1);
        SysUser sysUser = sysUserMapper.selectOne(userWrapper);
        
        // 3. 调用子API禁用账号
        String url = BASE_URL + "/v2/user";
        JSONObject urlParams = new JSONObject();
        urlParams.put("appuid", appUid);
        
        JSONObject requestBody = new JSONObject();
        requestBody.put("enabled", false);
        
        KuJiaLeHttpUtil.ApiResponse response = KuJiaLeHttpUtil.post(url, urlParams, requestBody.toJSONString());
        
        if (response.isSuccess() && "0".equals(response.getCode())) {
            if (sysUser != null) {
                // 4. 更新本地用户状态
                sysUser.setKujialeStatus(2); // 2-禁用
                int updateResult = sysUserMapper.updateById(sysUser);

                if (updateResult > 0) {
                    log.info("子账号禁用成功，appUid: {}, 用户ID: {}", appUid, sysUser.getUserId());
                } else {
                    log.error("更新本地用户状态失败，appUid: {}", appUid);
                    throw new ServiceException("更新本地用户状态失败");
                }
            }
        } else {
            log.error("子API调用失败，appUid: {}, 错误信息: {}", appUid, response.getMessage());
            throw new ServiceException("子账号禁用失败: " + response.getMessage());
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean enableKujialeAccount(String appUid) {
        log.info("开始启用子账号，appUid: {}", appUid);
        
        // 1. 验证参数
        if (StringUtils.isBlank(appUid)) {
            throw new ServiceException("子账号ID不能为空");
        }
        
        // 3. 查找本地用户
        LambdaQueryWrapper<SysUser> userWrapper = Wrappers.lambdaQuery();
        userWrapper.eq(SysUser::getKujialeId, appUid)
                .eq(SysUser::getKujialeStatus, 2) // 查找被禁用的用户
                .eq(SysUser::getIsBindKujiale, 1);
        SysUser sysUser = sysUserMapper.selectOne(userWrapper);
        
        // 3. 调用子API启用账号
        String url = BASE_URL + "/v2/user";
        JSONObject urlParams = new JSONObject();
        urlParams.put("appuid", appUid);
        
        JSONObject requestBody = new JSONObject();
        requestBody.put("enabled", true);
        
        KuJiaLeHttpUtil.ApiResponse response = KuJiaLeHttpUtil.post(url, urlParams, requestBody.toJSONString());
        
        if (response.isSuccess() && "0".equals(response.getCode())) {
            if (sysUser != null) {
                // 4. 更新本地用户状态
                sysUser.setKujialeStatus(1); // 1-启用
                int updateResult = sysUserMapper.updateById(sysUser);

                if (updateResult > 0) {
                    log.info("子账号启用成功，appUid: {}, 用户ID: {}", appUid, sysUser.getUserId());
                    return true;
                } else {
                    log.error("更新本地用户状态失败，appUid: {}", appUid);
                    throw new ServiceException("更新本地用户状态失败");
                }
            }
        } else {
            log.error("子API调用失败，appUid: {}, 错误信息: {}", appUid, response.getMessage());
            throw new ServiceException("子账号启用失败: " + response.getMessage());
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncKujialeAccountStatus(String appUid) {
        log.info("开始同步子账号状态，appUid: {}", appUid);

        // 1. 验证参数
        if (StringUtils.isBlank(appUid)) {
            throw new ServiceException("子账号ID不能为空");
        }

        // 2. 查找本地用户
        LambdaQueryWrapper<SysUser> userWrapper = Wrappers.lambdaQuery();
        userWrapper.eq(SysUser::getKujialeId, appUid)
                .eq(SysUser::getIsBindKujiale, 1);
        SysUser sysUser = sysUserMapper.selectOne(userWrapper);

        if (sysUser == null) {
            log.warn("未找到对应的本地用户，appUid: {}", appUid);
            return;
        }

        // 3. 调用子API查询账号状态
        String url = BASE_URL + "/v2/account/search/v2";
        JSONObject requestBody = new JSONObject();
        requestBody.put("appUids", new String[]{appUid});

        KuJiaLeHttpUtil.ApiResponse response = KuJiaLeHttpUtil.post(url, null, requestBody.toJSONString());

        if (response.isSuccess() && "0".equals(response.getCode())) {
            try {
                JSONObject data = JSONObject.from(response.getData());
                JSONArray result = data.getJSONArray("result");

                if (result != null && result.size() > 0) {
                    JSONObject accountInfo = result.getJSONObject(0);
                    JSONObject account = accountInfo.getJSONObject("account");

                    if (account != null) {
                        int kujialeStatus = account.getIntValue("status"); // 0->正常 1->删除 2->禁用 3->邀请中
                        int localStatus = sysUser.getKujialeStatus();

                        // 状态映射：子状态 -> 本地状态
                        int expectedLocalStatus;
                        switch (kujialeStatus) {
                            case 0: // 正常
                                expectedLocalStatus = 1; // 启用
                                break;
                            case 2: // 禁用
                                expectedLocalStatus = 2; // 禁用
                                break;
                            case 1: // 删除
                            case 3: // 邀请中
                                expectedLocalStatus = 3; // 删除
                                break;
                            default:
                                expectedLocalStatus = 0; // 未启用
                                break;
                        }

                        // 如果状态不一致，则同步
                        if (localStatus != expectedLocalStatus) {
                            log.info("发现状态不一致，appUid: {}, 子状态: {}, 本地状态: {}, 同步为: {}", 
                                    appUid, kujialeStatus, localStatus, expectedLocalStatus);

                            sysUser.setKujialeStatus(expectedLocalStatus);
                            int updateResult = sysUserMapper.updateById(sysUser);

                            if (updateResult > 0) {
                                log.info("账号状态同步成功，appUid: {}, 用户ID: {}, 新状态: {}", 
                                        appUid, sysUser.getUserId(), expectedLocalStatus);
                            } else {
                                log.error("账号状态同步失败，appUid: {}", appUid);
                                throw new ServiceException("账号状态同步失败");
                            }
                        } else {
                            log.info("账号状态已一致，appUid: {}, 状态: {}", appUid, localStatus);
                        }
                    } else {
                        log.warn("子返回的账号信息为空，appUid: {}", appUid);
                    }
                } else {
                    log.warn("子未找到对应账号，appUid: {}", appUid);
                }
            } catch (Exception e) {
                log.error("解析子账号状态失败，appUid: {}", appUid, e);
                throw new ServiceException("解析子账号状态失败: " + e.getMessage());
            }
        } else {
            log.error("查询子账号状态失败，appUid: {}, 错误信息: {}", appUid, response.getMessage());
            throw new ServiceException("查询子账号状态失败: " + response.getMessage());
        }
    }
}
